/**
 * Lottery system.
 *
 * Author:  David Qiu.
 * Email:   david@davidqiu.com
 * Website: http://www.davidqiu.com/
 *
 * Copyright (C) 2014, David Qiu. All rights reserved.
 */

var lottery;
if (!lottery) lottery = {};

if (!lottery.data) lottery.data = [];
lottery.timer = undefined;
lottery.current = undefined;

lottery.getRand = function (min, max) {
  return parseInt(Math.random() * (max-min + 1));
}

lottery.change = function () {
  lottery.current = lottery.getRand(0, lottery.data.length-1);
  if (lottery.data[lottery.current]) {
    $('#result').val(lottery.data[lottery.current].name);
  } else {
    $('#result').val('^_^');
  }
}

lottery.start = function () {
  $('#image').hide();
  clearInterval(lottery.timer);
  lottery.timer = setInterval('lottery.change()', 46);
}

lottery.stop = function () {
  clearInterval(lottery.timer);
  if (lottery.current !== undefined) {
    $('#image').attr('src', 'data/images/' + lottery.data[lottery.current].image);
    lottery.data.splice(lottery.current, 1);
    lottery.current = undefined;
    $('#image').show();
  }
}

// Append event handlers
$(document).ready(function () {
  $('#start').click(lottery.start);
  $('#stop').click(lottery.stop);
});
